import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 实现树的前序遍历,返回List<Integer>
 * User: xwl
 * Date: 2023-05-20
 * Time: 16:10
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution1 {
    public List<Integer> preorderTraversal(TreeNode root) {
        // 创建一个线性表ret用来存储节点的值
        List<Integer> ret = new ArrayList<>();
        // 判断树是否为空
        if (root == null) {
            return ret;
        }
        ret.add(root.val);
        List<Integer> leftTree = preorderTraversal(root.left);
        ret.addAll(leftTree);
        List<Integer> rightTree = preorderTraversal(root.right);
        ret.addAll(rightTree);
        // 返回
        return ret;
    }
}